package com.starnet.yarnmonitor.security.custom;


import com.starnet.yarnmonitor.yarn.handler.ApiException;
import com.starnet.yarnmonitor.security.entity.SysPermission;
import com.starnet.yarnmonitor.security.entity.SysUser;
import com.starnet.yarnmonitor.security.mapper.SysPermissionMapper;
import com.starnet.yarnmonitor.security.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @Data: 2019/10/30
 * @Des:
 */
@Component("jwtUserDetailsService")
public class JwtUserDetailsService implements UserDetailsService {

    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectByAccount(username);
        if (sysUser == null) {
            throw new ApiException("用户不存在");
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (sysUser != null) {
            //获取该用户所拥有的权限
            List<SysPermission> sysPermissions = sysPermissionMapper.selectListByUser(sysUser.getId());
            // 声明用户授权
            SysPermission empty = sysPermissions.get(0);
            if (empty!=null){
                sysPermissions.forEach(sysPermission -> {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(sysPermission.getPermissionCode());
                    grantedAuthorities.add(grantedAuthority);
                });
            }

        }

        return new User(sysUser.getAccount(),sysUser.getPassword(),sysUser.getEnabled(),sysUser.getNotExpired(),sysUser.getCredentialsNonExpired(),sysUser.getAccountNonLocked(),grantedAuthorities);
    }


}
